<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElForm, ElFormItem, ElDialog, ElSelect, ElOption, ElPagination } from 'element-plus';

// 商机数据
const businessData = ref([]);

// 搜索条件
const searchForm = reactive({
  opportunityId: '',
  customerName: '',
  status: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框状态
const dialogVisible = ref(false);
// 编辑模式
const editMode = ref(false);
// 当前编辑的商机ID
const currentBusinessId = ref(null);
// 表单数据
const formData = reactive({
  opportunityId: '',
  customerName: '',
  contactPhone: '',
  estimatedAmount: '',
  status: '',
  probability: '',
  expectedCloseDate: ''
});

// 表单验证规则
const rules = {
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 1, max: 50, message: '客户名称长度在1到50个字符之间', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  estimatedAmount: [
    { required: true, message: '请输入预计金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ]
};

// 表单引用
const businessFormRef = ref(null);

// 加载商机数据
const loadBusinessData = () => {
  // 模拟API请求，使用静态数据
  businessData.value = [
    {
      id: 1,
      opportunityId: 'OP1001',
      customerName: '北京科技有限公司',
      contactPhone: '13812345678',
      estimatedAmount: 150000,
      status: '进行中',
      probability: '70%',
      expectedCloseDate: '2025-12-31',
      createTime: '2025-10-01 10:00:00',
      updateTime: '2025-10-15 15:30:00'
    },
    {
      id: 2,
      opportunityId: 'OP1002',
      customerName: '上海网络科技公司',
      contactPhone: '13987654321',
      estimatedAmount: 200000,
      status: '已赢单',
      probability: '100%',
      expectedCloseDate: '2025-11-30',
      createTime: '2025-09-15 09:00:00',
      updateTime: '2025-10-10 14:20:00'
    },
    {
      id: 3,
      opportunityId: 'OP1003',
      customerName: '广州贸易有限公司',
      contactPhone: '13765432198',
      estimatedAmount: 80000,
      status: '进行中',
      probability: '50%',
      expectedCloseDate: '2026-01-15',
      createTime: '2025-10-10 11:20:00',
      updateTime: '2025-10-16 09:15:00'
    }
  ];
};

// 计算总数
const total = computed(() => businessData.value.length);

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + Number(pageSize.value);
  return businessData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
};

// 处理分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 打开添加对话框
const openAddDialog = () => {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editMode.value = true;
  currentBusinessId.value = row.id;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除商机
const deleteBusiness = (row) => {
  ElMessageBox.confirm('确定要删除该商机吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = businessData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      businessData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 保存商机
const saveBusiness = () => {
  businessFormRef.value.validate((valid) => {
    if (valid) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      
      if (editMode.value) {
        // 编辑模式
        const index = businessData.value.findIndex(item => item.id === currentBusinessId.value);
        if (index !== -1) {
          Object.assign(businessData.value[index], formData, { updateTime: now });
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加模式
        const newBusiness = {
          id: Date.now(), // 模拟生成唯一ID
          opportunityId: 'OP' + (1000 + businessData.value.length + 1),
          ...formData,
          createTime: now,
          updateTime: now
        };
        businessData.value.push(newBusiness);
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (businessFormRef.value) {
    businessFormRef.value.resetFields();
  }
  Object.keys(formData).forEach(key => {
    formData[key] = '';
  });
  currentBusinessId.value = null;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 组件挂载时加载数据
onMounted(() => {
  loadBusinessData();
});
</script>

<template>
  <div class="business-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="商机ID">
          <el-input v-model="searchForm.opportunityId" placeholder="请输入商机ID" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 150px;">
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已赢单" value="已赢单"></el-option>
            <el-option label="已输单" value="已输单"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="openAddDialog">新增商机</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="currentPageData" stripe style="width: 100%">
        <el-table-column prop="opportunityId" label="商机ID" width="120"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="180"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="150"></el-table-column>
        <el-table-column prop="estimatedAmount" label="预计金额" width="120">
          <template #default="{ row }">
            {{ row.estimatedAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column prop="probability" label="成交概率" width="100"></el-table-column>
        <el-table-column prop="expectedCloseDate" label="预计成交日期" width="150"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" link @click="deleteBusiness(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editMode ? '编辑商机' : '新增商机'"
      width="600px"
    >
      <el-form
        ref="businessFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="formData.customerName" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="预计金额" prop="estimatedAmount">
          <el-input v-model="formData.estimatedAmount" placeholder="请输入预计金额" type="number"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已赢单" value="已赢单"></el-option>
            <el-option label="已输单" value="已输单"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成交概率">
          <el-input v-model="formData.probability" placeholder="请输入成交概率"></el-input>
        </el-form-item>
        <el-form-item label="预计成交日期">
          <el-input v-model="formData.expectedCloseDate" placeholder="请输入预计成交日期"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveBusiness">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.business-container {
  padding: 20px;
}

.search-area {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-area {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>